#include "place_list_view.h"
#include "ui_place_list_view.h"

#include "place_view.h"

PlaceListView::PlaceListView(QWidget *parent) :
    ViewBase(parent),
    ui(new Ui::PlaceListView),
    placeView_(0)
{
    ui->setupUi(this);

    QAction *backSoftkeyAction = new QAction(QString("Back"), this);
    backSoftkeyAction->setSoftKeyRole(QAction::NegativeSoftKey);
    QObject::connect(backSoftkeyAction, SIGNAL(triggered()),
                     this, SLOT(hide()));
    addAction(backSoftkeyAction);

    connect(ui->lstPlaceList, SIGNAL(itemActivated(QListWidgetItem*)),
            this, SLOT(showPlace(QListWidgetItem*)));
}

PlaceListView::~PlaceListView()
{
    delete ui;
    if (placeView_) {
        delete placeView_;
    }
}


void PlaceListView::IssueRequest() {
  QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
  RequestMethod request(this, QString("xml"), QString("Places.getByCategoryAndSubcate"));
  request.AddParam(QString("category"), category_.cn_cate);
  request.AddParam(QString("subcate"), subCategory_.cn_cate);
  request.AddParam(QString("city"), QString("北京"));

  places_.clear();

  ui->lstPlaceList->clear();

  if (handler_) {
    handler_->IssueRequest(request);
  }
}

int PlaceListView::ProcessResult(RequestMethod &r, QDomElement &e) {
  int re = parse_result(e);
  if (re == 0) {
    for (int i = 0; i < places_.count(); ++i) {
      place &p = places_[i];
      ui->lstPlaceList->addItem(p.name);
    }
  }

  return re;
}


int PlaceListView::parse_result(QDomElement &e) {
  QDomNodeList l = e.childNodes();
  for (int i = 0; i < l.count(); ++i) {
    QDomElement el = l.at(i).toElement();
    if (el.nodeName() == QString("places")) {
      parse_places(el);
    }
  }

  return 0;
}

int PlaceListView::parse_places(QDomElement &e) {
  QDomNodeList l = e.childNodes();
  for (int i = 0; i < l.count(); ++i) {
    QDomElement el = l.at(i).toElement();
    if (el.nodeName() == QString("place")) {
      place p;
      parse_place(el, p);
      places_.push_back(p);
    }
  }

  return 0;
}

void PlaceListView::showPlace(QListWidgetItem *item) {
    for (int i = 0; i < places_.count(); ++i) {
        place &p = places_[i];
        if (p.name == item->text()) {
            if (!placeView_) {
                placeView_ = new PlaceView(this);
                placeView_->SetRequestHandler(handler_);
            }
            placeView_->SetPlace(p);
            placeView_->Show();
            placeView_->IssueRequest();
            return;
        }
    }
}
